<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataItem.deviceNumber || ''} / ${dataItem.belongDate} / ${dataItem.shiftName || ''}-详情`"
		width="1200px"
		:show-confirm-btn="false"
		:show-cancel-btn="false"
		:show-close-btn="true"
		@on-close="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
	>
		<div class="flex-end-center margin-bottom-10">
			<jk-date-picker
				v-model="searchParams.fromDate"
				type="date"
				:disabled-future-time="true"
				:clearable="false"
				placeholder="班次开始日期"
				size="small"
				class="search-bar-item-size2 margin-5-0 item-gap"
			></jk-date-picker>
			<jk-select
				v-model="searchParams.fromShiftCode"
				:option-list="searchOptionConfig.shiftList"
				size="small"
				placeholder="开始班次"
				class="search-bar-item-size1 margin-5-0 item-gap"
			></jk-select>
			<jk-date-picker
				v-model="searchParams.toDate"
				type="date"
				:disabled-future-time="true"
				:clearable="false"
				placeholder="班次结束日期"
				size="small"
				class="search-bar-item-size2 margin-5-0 item-gap"
			></jk-date-picker>
			<jk-select
				v-model="searchParams.toShiftCode"
				:option-list="searchOptionConfig.shiftList"
				size="small"
				placeholder="结束班次"
				class="search-bar-item-size1 margin-5-0 item-gap"
			></jk-select>
			<!--<jk-select v-model="searchParams.workshopId" :clearable="false" placeholder="区域" :option-list="workshopList" size="small" class="search-bar-item-size1 margin-5-0 item-gap" @change="onDateChange"></jk-select>-->
			<!-- <jk-date-picker
				v-model="searchParams.belongDates"
				type="daterange"
				:disabled-future-time="true"
				:clearable="false"
				placeholder="日期"
				size="small"
				class="search-bar-item-size4 item-gap"
			></jk-date-picker>
			<jk-select
				v-model="searchParams.shiftCode"
				:option-list="searchOptionConfig.shiftList"
				size="small"
				placeholder="班次"
				class="search-bar-item-size1 item-gap"
			></jk-select>
			<el-time-picker
				v-model="pickerTime"
				is-range
				value-format="HH:mm:ss"
				size="small"
				range-separator="至"
				style="width: 280px"
				class="margin-5-0 item-gap"
				start-placeholder="班次开始时间"
				end-placeholder="班次结束时间"
			>
			</el-time-picker> -->
			<!--<jk-select v-model="searchParams.duration" placeholder="时长排序" :option-list="[{id: 'asc', name:'正序'},{id: 'desc', name:'倒序'}]" size="small" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>-->
			<jk-input
				v-model="searchParams.deviceNumber"
				class="search-bar-item-size2 item-gap"
				placeholder="机台号"
				size="small"
				clearable
				@on-enter="onSearchBtn"
			/>
			<jk-select
				v-model="searchParams.position"
				label-key-name="id"
				placeholder="面位"
				:option-list="searchOptionConfig.machineFaceList"
				size="small"
				class="search-bar-item-size1 item-gap"
			></jk-select>
			<!--<jk-input v-model="searchParams.startIngotNo" class="search-bar-item-size1 margin-5-0 item-gap" placeholder="开始锭号" size="small" clearable @blur="onIngotNumberChange($event,'startIngotNo')" />-->
			<!--<jk-input v-model="searchParams.endIngotNo" class="search-bar-item-size1 margin-5-0 item-gap" placeholder="结束锭号" size="small" clearable @blur="onIngotNumberChange($event,'endIngotNo')" />-->
			<jk-search-button @click="onSearchBtn"></jk-search-button>
		</div>
		<jk-table
			border
			:data="tableData"
			:footer-method="footerMethod"
			:show-footer="true"
			:loading="tableLoading"
			:height="400"
		>
			<vxe-column
				title="日期时间"
				align="left"
				field="belongDate"
				:width="140"
			/>
			<vxe-column
				title="屏幕班次"
				align="left"
				field="screenShiftName"
				:min-width="80"
			/>
			<vxe-column
				title="机台号"
				align="left"
				field="deviceNumber"
				:min-width="80"
			/>
			<vxe-column
				title="面位"
				align="left"
				field="position"
				:min-width="80"
			/>
			<vxe-column
				title="锭号"
				align="left"
				field="ingotNo"
				:min-width="80"
			/>
			<vxe-column
				title="弱捻开始时间"
				align="left"
				field="startTime"
				:width="160"
			/>
			<vxe-column
				title="断头结束时间"
				align="left"
				field="endTime"
				:width="160"
			/>
			<vxe-column
				title="弱捻(分)"
				align="left"
				field="duration"
				:min-width="80"
			>
				<template #header>
					<div style="display: flex">
						<span>弱捻(分)</span>
						<span
							style="
                                cursor: pointer;
                                display: flex;
                                align-items: center;
                            "
							@click="toggleSort('duration')"
						>
							{{
								sortOrders.duration === "asc"
									? "⬆"
									: sortOrders.duration === "desc"
										? "⬇"
										: "⇅"
							}}
						</span>
					</div>
				</template>
			</vxe-column>
		</jk-table>
		<!-- 分页组件 -->
		<footer ref="box2" class="flex-end-center margin-top-10">
			<jk-page
				:page-index="searchParams.pageNo"
				:page-sizes="searchParams.pageSizes"
				:page-size="searchParams.pageSize"
				:total="totalCount"
				@on-change="onPageChange"
			/>
		</footer>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import { iotSpinWeakTwistPage } from '@/api/statistic/spindleReports';
    import { workforceManagementShiftGetByTime } from '@/api/schedule/shift';
    import { pageConfig } from '/src/utils/jk/jk-tool';
    import XEUtils from 'xe-utils';

    export default {
        name: 'MachineArchives',
        props: {
            searchOptionConfig: {
                type: Object,
                default() {
                    return {
                        shiftList: [],
                        machineFaceList: []
                    };
                }
            },
            isRealTime: {
                type: Boolean,
                default: false
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataItem: {
                type: Object,
                default() {
                    return {};
                }
            }
        },
        mixins: [calHeight],
        data() {
            return {
                totalCount: null,
                apiItem: {
                    page: iotSpinWeakTwistPage
                },
                sortOrders: {
                    duration: null
                },
                pickerTime: [],
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize
                },
                showDialog: false,
                tableLoading: false,
                tableData: []
            };
        },
        methods: {
            footerMethod({ columns, data }) {
                const keys = ['ingotNo', 'duration'];
                const hasData = this.tableData.length > 0;
                const totalWeakTwistQty = hasData ? this.tableData[0].totalWeakTwistQty : '';
                const totalWeakTwistTime = hasData ? this.tableData[0].totalWeakTwistTime : '';
                return [
                    columns.map((column, columnIndex) => {
                        switch (columnIndex) {
                        case 0:
                            return '合计';
                        case 5:
                            return totalWeakTwistQty;
                        case 8:
                            return totalWeakTwistTime;
                        default:
                            return keys.includes(column.field) ? XEUtils.sum(data, column.field) : null;
                        }
                    })
                ];
            },
            toggleSort(field) {
                // 重置所有排序状态
                Object.keys(this.sortOrders).forEach((key) => {
                    if (key !== field) {
                        this.sortOrders[key] = null;
                    }
                });
                // 切换当前字段的排序状态
                const currentOrder = this.sortOrders[field];

                switch (currentOrder) {
                case null:
                    this.sortOrders[field] = 'asc';
                    this.searchParams.ascField = field;
                    this.searchParams.descField = null;
                    break;
                case 'asc':
                    this.sortOrders[field] = 'desc';
                    this.searchParams.ascField = null;
                    this.searchParams.descField = field;
                    break;
                case 'desc':
                    this.sortOrders[field] = null;
                    this.searchParams.ascField = null;
                    this.searchParams.descField = null;
                    break;
                }
                // 如果未设置排序类型，则请求更新列表
                if (!this.searchParams.sortType) {
                    this.getListRequest();
                }
            },
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.totalCount = 1;
                this.getListRequest();
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            getListRequest() {
                this.tableData = [];
                this.tableLoading = true;
                const params = JSON.parse(JSON.stringify(this.searchParams));
                const propertiesToDelete = [
                    'belongDate',
                    'shiftCode',
                    'screenShift',
                    'kid',
                    'screenShiftName',
                    'weakTwistCount',
                    'deviceWeakTwistCount'
                ];
                propertiesToDelete.forEach((prop) => delete params[prop]);
                // params.belongDates = params.belongDates.map((date, index) => {
                //     const defaultTime = index === 0 ? '00:00:00' : '23:59:59';
                //     const time =
                //         this.pickerTime && this.pickerTime.length > 0
                //             ? this.pickerTime[index]
                //             : defaultTime;
                //     if (params.shiftCode === 2 && index === 1) {
                //         const dateObj = new Date(date); // 将日期字符串转为Date对象
                //         dateObj.setDate(dateObj.getDate() + 1); // 增加一天
                //         date = `${dateObj.getFullYear()}-${(dateObj.getMonth() + 1).toString().padStart(2, '0')}-${dateObj.getDate().toString().padStart(2, '0')}`;
                //     }
                //     return `${date} ${time}`;
                // });

                return this.apiItem['page'](params).then((res) => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.totalCount = res.data.count;
                    }
                });
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    const { belongDate, shiftCode, deviceNumber, position } =
                        this.dataItem;
                    this.searchParams = {
                        ...this.searchParams,
                        fromDate: belongDate,
                        toDate: belongDate,
                        fromShiftCode: shiftCode,
                        toShiftCode: shiftCode,
                        deviceNumber,
                        position
                    };
                    this.$nextTick(() => {
                        this.getListRequest();
                    });
                }
            }
        // 'searchParams.shiftCode': {
        //     handler(val) {
        //         const { shiftList } = this.searchOptionConfig;
        //         const selectedShift = shiftList.find((i) => i.id === val);
        //         if (selectedShift) {
        //             const { beginHour, endHour } = selectedShift;
        //             this.pickerTime = [beginHour, endHour]; // 直接赋值
        //         }
        //     },
        //     immediate: true
        // }
        }
    };
</script>
